/**
 * 演示同步迭代器和异步迭代器
 */
class Emitter {
  syncIdx: number;
  asyncIdx: number;
  max: number;

  constructor(max: number) {
    this.syncIdx = 0;
    this.asyncIdx = 0;
    this.max = max;
  }

  /**
   * 同步迭代器
   */
  *[Symbol.iterator]() {
    while (this.syncIdx < this.max) {
      yield this.syncIdx++;
    }
  }

  /**
   * 异步迭代器
   */
  *[Symbol.asyncIterator]() {
    while (this.asyncIdx < this.max) {
      yield new Promise<number>((reso) => {
        setTimeout(() => {
          reso(this.asyncIdx++);
        }, Math.random() * 1000);
      });
    }
  }
}

const emitter = new Emitter(5);

// 同步迭代器函数

function syncIteFn() {
  const syncIter = emitter[Symbol.iterator]();
  for (const num of syncIter) {
    console.log('同步:', num);
  }
}

// 异步迭代器函数
async function asyncIteFn() {
  const asyIter = emitter[Symbol.asyncIterator]();
  for await (const num of asyIter) {
    console.log('异步:', num);
  }
}

syncIteFn();
console.log('------------------');
asyncIteFn();
